<template>
  <div class="approval-list-container">
    <!--查询-->
    <el-row>
      <el-input style="width:200px;margin-right: 10px" v-model="tableQuery.msg" placeholder="名称" ></el-input>
      <el-tooltip class="item" content="搜索" placement="top">
        <el-button icon="el-icon-search" circle @click="fetchData()"></el-button>
      </el-tooltip>
    </el-row>
    <div style="margin-bottom: 30px;"></div>
    <el-tooltip content="批量通过表单审批" placement="top" v-if="batchOperate">
      <el-button size="mini" type="primary" @click="batchConfirm"><i class="el-icon-circle-check" /> 批量通过({{selectionRows.length}})</el-button>
    </el-tooltip>
    <el-tooltip content="批量退回表单审批" placement="top" v-if="batchOperate">
      <el-button size="mini" type="danger" @click="batchRefuse"><i class="el-icon-circle-close"  /> 批量退回({{selectionRows.length}})</el-button>
    </el-tooltip>
    <!--列表-->
    <el-table ref="approvalTable"
              style="width: 100%;margin-top: 10px"
              :data="tableData"
              v-loading.body="tableLoading"
              row-key="form_no"
              @selection-change="tbSelChange"
              element-loading-text="Loading"
              border fit highlight-current-row>
      <el-table-column type="selection" width="80" :reserve-selection="true"></el-table-column>
      <el-table-column prop="form_no" label="表单号" width="200"></el-table-column>
      <el-table-column prop="module_name" label="模块" ></el-table-column>
      <el-table-column prop="orgnization_name" label="组织"></el-table-column>
      <el-table-column prop="date" label="表单日期"></el-table-column>
      <el-table-column prop="msg" label="审批内容" width="350" show-overflow-tooltip></el-table-column>
      <el-table-column prop="user_name" label="发起人"></el-table-column>
      <el-table-column prop="created_at" label="创建时间" ></el-table-column>
      <el-table-column prop="status_name" label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="tableQuery.status=='check'?'danger':'success'" size="mini">{{scope.row.status_name}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-tooltip content="审批/查看" placement="top">
            <el-link icon="el-icon-edit" @click="handleUpdate(scope.$index,scope.row)" >{{editBtnTitle}}</el-link>
          </el-tooltip>
          <span style="margin:10px">|</span>
          <el-tooltip content="删除" placement="top">
            <el-link type="danger" icon="el-icon-delete" @click="handleDelete(scope.$index,scope.row)">删除</el-link>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-bottom: 30px;"></div>
    <!--分页-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="tablePage.current"
      :page-sizes="[20, 30, 40, 50, 60]"
      :page-size="tablePage.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tablePage.total">
    </el-pagination>
    <!--弹出窗口：编辑角色-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="80%">
      <el-dialog title="表单详情" :visible.sync="approvalDetailShow" width="80%" append-to-body>
        <el-card class="box-card">
          <el-date-picker
            v-model="temp.date"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd" readonly></el-date-picker>
          <div style="margin-bottom: 30px"></div>
          <el-tabs v-model="activeGroup">
            <el-tab-pane v-for="(item, index) in tabsData" :key="index" :label="item.group_name" :name="item.group_name">
              <el-form  label-position="left" label-width="120px">
                <el-form-item>
                  <el-row :gutter="10">
                    <el-col :span="5" class="field-header-col">当前值</el-col>
                    <el-col :span="5" class="field-header-col">月累计</el-col>
                    <el-col :span="5" class="field-header-col">年累计</el-col>
                    <el-col :span="5" class="field-header-col">单位</el-col>
                  </el-row>
                </el-form-item>
                <el-form-item v-for="(field, idx) in item.list" :key="idx" :label="field.alias">
                  <el-row :gutter="10">
                    <el-col :span="5">
                      <el-input type="number" v-model.number="field.value" placeholder="请输入" readonly/>
                    </el-col>
                    <el-col :span="5">
                      <el-input type="number" v-model.number="field.month_value" readonly/>
                    </el-col>
                    <el-col :span="5">
                      <el-input type="number" v-model.number="field.year_value"  readonly />
                    </el-col>
                    <el-col :span="5">
                      <el-input v-model="field.messure" readonly />
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-card>
        <div slot="footer" class="dialog-footer">
          <el-button @click="approvalDetailShow = false">关闭</el-button>
        </div>
      </el-dialog>

      <el-form v-loading="detailLoading" :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="150px" >
        <el-form-item label="表单号" prop="form_no">
          <el-tooltip content="查看表单详情">
            <el-link type="primary" @click="checkDetail">{{temp.form_no}}  <i class="el-icon-view el-icon--right"></i></el-link>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="模块" prop="module_name" >
          <el-input v-model="temp.module_name" readonly></el-input>
        </el-form-item>
        <el-form-item label="组织" prop="orgnization_name" >
          <el-input v-model="temp.orgnization_name" readonly></el-input>
        </el-form-item>
        <el-form-item label="表单日期" prop="date" >
          <el-input v-model="temp.date" readonly></el-input>
        </el-form-item>
        <el-form-item label="审批内容" prop="msg">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}"  v-model="temp.msg" readonly>
          </el-input>
        </el-form-item>
        <el-form-item label="当前状态" prop="status_name" >
          <el-input v-model="temp.status_name" readonly></el-input>
        </el-form-item>
        <el-form-item label="发起人" prop="user_name" >
          <el-input v-model="temp.user_name" readonly></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 6}"  v-model="temp.remark">
          </el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="this.tableQuery.status!='complete'"  type="danger" @click="updateData(false)">退回</el-button>
        <el-button v-if="this.tableQuery.status!='complete'"  type="primary" @click="updateData(true)">同意</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

  import articleApi from "@/api/article"
  import dailyApi from "@/api/daily_data"
  import { resetTemp } from '@/utils'
  import { confirm } from '@/utils/constants'
  import debounce from 'lodash/debounce'


  export default {
    name: 'ApprovalList',
    data() {
      return {
        tableLoading:false,
        detailLoading:false,
        tableData: [],
        selectionRows:[],
        tableQuery:{
          status: null,
          msg:null
        },
        tablePage: {
          current: null,
          pages: null,
          size:null,
          total: null
        },
        dialogFormVisible: false,
        dialogStatus: '',
        temp: {
          id: null,
          date:null,
          form_no: null,
          module_name: null,
          date:null,
          orgnization_name:null,
          msg: null,
          status:null,
          status_name: null,
          step:null,
          user_id:null,
          user_name:null,
          opinion:null,
          remark:null
        },
        approvalDetailShow:false,
        tabsData:[],
        activeGroup:'',
        textMap: {
          update: '审批处理',
          detail: '审批查看'
        },
        rules: {
          name: [{ required: true, message: '必填', trigger: 'blur' }]
        },
      }
    },
    computed:{
      editBtnTitle(){
        return this.tableQuery.status=='complete'?'查看':'审批'
      },
      batchOperate(){
        return this.selectionRows.length>0
      }
    },
    created(){
      const status = this.$route.params.status
      this.tableQuery.status = status?status:'check'
      document.title = status=='check'?'待处理':'已完成'
      this.fetchData(1)
    },

    watch:{
      //延时查询
      'tableQuery.msg': debounce( function(){
        this.fetchData()
      },500),
    },//watch

    methods: {
      //分页
      handleSizeChange(val) {
        this.tablePage.size = val;
        this.fetchData();
      },
      handleCurrentChange(val) {
        this.tablePage.current = val;
        this.fetchData();
      },
      //查询
      fetchData(page) {
        if (page)
          this.tablePage.current=page
        this.tableLoading = true
        articleApi.approvalQuery(this.tableQuery, this.tablePage).then(res=>{
          console.log(res.data)
          let roledata = res.data
          this.tableData = roledata.data
          this.tablePage.total=roledata.total
          if(!this.tablePage.current)
            this.tablePage.current=1
          if (!this.tablePage.size)
            this.tablePage.size=20
          this.tableLoading = false
        }).catch(err=>{
          this.tableData=[]
          resetTemp(this.tablePage)
          resetTemp(this.tableQuery)
          this.tableLoading=false
        })
      },
      checkDetail(){
        this.detailLoading=true
        const rqData={form_no:this.temp.form_no}
        dailyApi.dailyDetail(rqData).then(res=>{
          const allGroups = res.data
          this.tabsData = this.editedTabsData(allGroups.data)
          if (this.tabsData.length)
            this.activeGroup = this.tabsData[0].group_name
          this.detailLoading=false
          this.approvalDetailShow=true
        })

      },
      tbSelChange(rows){
        this.selectionRows = rows
      },
      handleUpdate(idx,row) {
        this.temp = Object.assign({}, row) // copy obj
        this.dialogStatus = this.tableQuery.status=='check'?'update':'detail'
        this.dialogFormVisible = true
        this.$nextTick(() => this.$refs['dataForm'].clearValidate())
      },
      updateData(agree) {
        this.$refs['dataForm'].validate((valid) => {
          if (!valid) return;
            this.temp.opinion=agree?'agree':'disagree'
            const tempData = Object.assign({}, this.temp)//copy obj
            articleApi.approvalStore(tempData).then(res => {
              this.dialogFormVisible = false
              this.$message.success('审批成功')
              this.$store.dispatch('user/getNotify')
              this.fetchData()
            })
        })
      },
      //删除
      handleDelete(idx,row) {
        this.$confirm('您确定要永久删除该审批？', '提示', confirm).then(() => {
          articleApi.approvalDelete( row.id ).then(res => {
            this.tablePage.total--
            this.dialogFormVisible = false
            const page_surplus = this.tablePage.total % this.tablePage.size
            const max_page = Math.ceil(this.tablePage.total/this.tablePage.size)
            if (!page_surplus&&this.tablePage.current>max_page)
              this.tablePage.current--
            this.$message.success("删除成功")
            this.fetchData()
          })
        }).catch(() => {
          this.$message.info('已取消删除')
        })
      },
      editedTabsData(gData){
          let tagGroups=[]
          for (let gidx in gData){
            const taglist = gData[gidx].data
            let flist = []
            for (let tidx in taglist){
              const tag = taglist[tidx]
              this.temp.date=tag.date
              this.temp.form_no=tag.form_no
              this.temp.status=tag.status
              flist.push({
                alias:tag.alias?tag.alias:tag.dcs_standard_name,
                cn_name:tag.dcs_standard_name,
                messure:tag.messure,
                dcs_standard_id:tag.dcs_standard_id,
                month_value:tag.month_value,
                year_value:tag.year_value,
                is_count:tag.is_count?1:0,
                is_month:tag.is_month,
                value:tag.value,
                desc:tag.description
              })
            }
            tagGroups.push({
              group_name:gData[gidx].name,
              list:flist
            })
          }
          return tagGroups
        },
      batchConfirm(){
        this.batchFunc('agree','批量通过')
      },
      batchRefuse(){
        this.batchFunc('disagree','批量退回')
      },
      batchFunc(opinion, remark){
        const fnos = this.selectionRows.map(row=> row.form_no).join(',')
        const tempData = {
          opinion:opinion,
          form_no:fnos,
          remark:remark
        }
        articleApi.approvalMutilStore(tempData).then(res => {
          this.dialogFormVisible = false
          this.$message.success('批量操作成功')
          this.$refs['approvalTable'].clearSelection()
          this.selectionRows=[]
          this.$store.dispatch('user/getNotify')
          this.fetchData()
        })
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss">
  .approval-list-container{
    padding: 5px;

    .el-table__header .has-gutter tr .el-table-column--selection .cell .el-checkbox:after {
      content: "  全选";
    }

  }

</style>
